package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.MyAutowired;
import com.lagou.edu.mvcframework.annotations.MyController;
import com.lagou.edu.mvcframework.annotations.MyRequestMapping;
import com.lagou.edu.mvcframework.annotations.MyService;
import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zx
 * @date 2021/7/26 20:07
 * @description
 */
public class MyDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();// 全限定类名

    private Map<String, Object> ioc = new HashMap<>();

   // private Map<String,Method> handlerMapping = new HashMap<>();
    private List<Handler> handlerList =  new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1.加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2.扫描注解类
        doScan(properties.getProperty("scanPackage"));
        // 3.初始化bean对象
        doInstance();
        // 4.依赖注入
        doAutowired();
        // 5.构造handleMap关系  处理器映射器 url 找方法
        initHandlerMapping();
        System.out.println("初始化完成");
    }

    // 处理器映射器开发
    private void initHandlerMapping() {
        if (ioc.isEmpty())  return;
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            // 跳过其他层
            if (!aClass.isAnnotationPresent(MyController.class))  continue;

            String baseUrl ="";
            if (aClass.isAnnotationPresent(MyRequestMapping.class)) {
                MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();
            }

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(MyRequestMapping.class)) continue;
                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String methodUrl = annotation.value();
                String url =baseUrl + methodUrl;
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else {
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }
                if (method.isAnnotationPresent(Security.class)) {
                    Security securityAnnotation = method.getAnnotation(Security.class);
                    String[] value = securityAnnotation.value();
                    Set<String> permission = new HashSet<String>(Arrays.asList(value));
                    // 记录权限
                    handler.setPermissions(permission);
                }
                handlerList.add(handler);
            }
        }
    }

    // 依赖注入
    private void doAutowired() {
        if (ioc.isEmpty())  return;
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (!declaredField.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                // 有著姐
                MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
                String beanName = annotation.value();
                if ("".equals(beanName.trim())) {
                    beanName = declaredField.getType().getName();
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    // 初始化bean对象 及IOC
    private void doInstance() {
        if (classNames.size() == 0) return;
        try {
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(MyController.class)) {
                    // 按首字母小写 暂不取 value
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService serviceAnnotation = aClass.getAnnotation(MyService.class);
                    String beanName = serviceAnnotation.value();

                    // 判断是否指定Id
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }
                    // 判断是否存在接口
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int i = 0; i < interfaces.length; i++) {
                        Class<?> anInterface = interfaces[i];
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }

                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 首字母小写
    private String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return str;
    }


    // 扫描类  scanPackage:com.lagou.demo  ----->磁盘上的文件夹（File类获取） 磁盘上用的AA/BB/cc
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());// 相当于 根目录增加目录AA/BB/cc/dd
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }

    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收处理情妾
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求
        resp.setContentType("text/html; charset=UTF-8");
        // 获取url
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404找不到");
            return;
        }

        //方法参数 获取
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        Object[] paramValues = new Object[parameterTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 这里进行权限 判断
        String username = req.getParameter("username");
        if (!handler.isAllowAccess(username)) {
            resp.getWriter().write(username +":用户无权限访问该服务!!!");
            return;
        }

        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ","); // 1,2
            // 填充参数
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            
            paramValues[index] = value;
        }
        // 特殊处理
        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[requestIndex] = req;

        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[responseIndex] = resp;

        try {
            handler.getMethod().invoke(handler.getController(),paramValues);
            resp.getWriter().write("调用完成");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerList.isEmpty())  return null;
        String url = req.getRequestURI();
        for (Handler handler : handlerList) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }
}
